<template>
  <div style="margin: 40px 20px">
    <!-- 就诊人管理卡片 -->
    <el-card
      v-if="!isAdd"
      class="box-card"
      style="width: 960px; min-height: 600px"
    >
      <template #header>
        <div class="header">
          <div class="title">
            <span>就诊人管理</span>
          </div>
          <div class="btn">
            <el-button type="success" @click="isAdd = true">
              <el-icon style="margin-right: 10px"><User /></el-icon>
              添加就诊人</el-button
            >
          </div>
        </div>
      </template>
      <template #default>
        <div class="allAuthCard" v-if="patientInfoList">
          <!-- 已添加就诊人卡片 -->
          <el-card
            class="box-card"
            style="width: 295px; height: 390px; margin-right: 10px"
            v-for="patientInfo in patientInfoList"
            ::key="patientInfo.id"
          >
            <template #header>
              <div class="cardHeader">
                <div>
                  <span style="background-color: #fff; margin-right: 5px">{{
                    patientInfo.isInsure == 1 ? "自费" : "医保"
                  }}</span>
                  <span style="font-size=16px;">{{ patientInfo.name }}</span>
                </div>
                <div>
                  <!-- 点击修改跳转到添加就诊人信息页,需要传入当前选中的就诊人id和type为edit类型 -->
                  <div ref="editBtn" data-type="edit" style="display=flex">
                    <el-button
                      type="primary"
                      circle
                      @click="updatePatient(patientInfo.id)"
                      ><el-icon><Edit /></el-icon>
                    </el-button>
                    <!-- 删除就诊人信息 -->
                    <!-- <el-popconfirm title="确定要删除吗?">
                      <template #reference> -->
                        <el-button
                          type="danger"
                          circle
                          @click="deletePatient(patientInfo.id)"
                          ><el-icon><Delete /></el-icon
                        ></el-button>
                      <!-- </template>
                    </el-popconfirm> -->
                  </div>
                </div>
              </div>
            </template>
            <!-- 已添加就诊人详细信息 -->
            <div>
              <el-descriptions
                :column="1"
                size="default"
                direction="horizontal"
              >
                <el-descriptions-item label="证件类型:">{{
                  patientInfo.certificatesType === "1" ? "身份证" : "户口本"
                }}</el-descriptions-item>
                <el-descriptions-item label="证件号码:">{{
                  patientInfo.certificatesNo
                }}</el-descriptions-item>
                <el-descriptions-item label="用户性别:">{{
                  patientInfo.sex === 1 ? "男" : "女"
                }}</el-descriptions-item>
                <el-descriptions-item label="出生日期:">
                  {{ patientInfo.birthdate }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号码:"
                  >{{ patientInfo.phone }}
                </el-descriptions-item>
                <el-descriptions-item label="婚姻状况:"
                  >{{ patientInfo.isMarry === 1 ? "未婚" : "已婚" }}
                </el-descriptions-item>
                <el-descriptions-item label="当前住址:"
                  >{{ patientInfo.param.provinceString }}/{{
                    patientInfo.param.cityString
                  }}/{{ patientInfo.param.districtString }}
                </el-descriptions-item>
                <el-descriptions-item label="详细地址:"
                  >{{ patientInfo.param.fullAddress }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
        </div>
      </template>
    </el-card>
    <!-- 添加就诊人 -->
    <!-- 点击就诊人信息卡片右上角的添加就诊人按钮显示该卡片 -->
    <el-card v-else class="box-card" style="width: 960px">
      <template #header>
        <div class="header">
          <div class="title">
            <span>添加就诊人</span>
          </div>
        </div>
      </template>
      <div>
        <div>
          <el-divider content-position="left">就诊人信息</el-divider>
        </div>
        <el-form style="margin-left: 120px">
          <el-form-item label="用户姓名" required>
            <el-input
              v-model="formData.name"
              placeholder="鲁大海"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item label="证件类型" required>
            <el-select v-model="formData.certificatesType">
              <el-option label="身份证" :value="1"></el-option>
              <el-option label="户口本" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码" required>
            <el-input
              v-model="formData.certificatesNo"
              placeholder="121212121212121212"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户性别" required>
            <el-radio-group v-model="formData.sex" class="ml-4">
              <el-radio :label="0" size="large">女</el-radio>
              <el-radio :label="1" size="large">男</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期" required>
            <div class="block">
              <el-date-picker
                v-model="formData.birthdate"
                type="date"
                placeholder="1989-01-27"
                size="default"
              />
            </div>
          </el-form-item>
          <el-form-item label="手机号码" required>
            <el-input
              v-model="formData.phone"
              placeholder="12121212121"
              style="width: 380px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <div>
          <el-divider content-position="left"
            >建档信息（完善后部分医院首次就诊不排队建档）</el-divider
          >
        </div>
        <el-form style="margin-left: 120px">
          <el-form-item label="婚姻状况" required>
            <el-radio-group v-model="formData.isMarry" class="ml-4">
              <el-radio :label="1" size="large">未婚</el-radio>
              <el-radio :label="0" size="large">已婚</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自费/医保" required>
            <el-radio-group v-model="formData.isInsure" class="ml-4">
              <el-radio :label="1" size="large">自费</el-radio>
              <el-radio :label="2" size="large">医保</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="当前住址" required>
            <div class="m-4">
              <el-cascader
                :props="props"
                :options="provinceList"
                :model-value="formData.addressSelected"
                @change="selectAddress"
                ref="cascader"
              />
            </div>
          </el-form-item>
          <el-form-item label="详细地址" required>
            <el-input
              v-model="formData.address"
              placeholder="同人医院"
              style="width: 380px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div>
          <el-divider content-position="left">联系人信息（选填）</el-divider>
        </div>
        <el-form style="margin-left: 120px">
          <el-form-item label="用户姓名">
            <el-input
              v-model="formData.contactsName"
              placeholder="李涛"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item label="证件类型">
            <el-select v-model="formData.contactsCertificatesType">
              <el-option label="身份证" value="1"></el-option>
              <el-option label="户口本" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input
              v-model="formData.contactsCertificatesNo"
              placeholder="1211211212121212"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input
              v-model="formData.contactsPhone"
              placeholder="12121212121"
              style="width: 380px"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-left: 80px">
            <el-button type="primary" @click="addPatient">提交</el-button>
            <el-button @click="rewriteForm">重写</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Patient",
});
</script>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { Edit } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import {
  reqCityList,
  reqAddPatient,
  reqPatientList,
  reqUpdatePatient,
  reqPatientAuth,
  reqDeletePatient,
} from "@/api/user";
import type {
  addPatientType,
  cityItemType,
  patientInfoItemType,
  updatePatientType,
} from "@/api/user";
import type { CascaderProps } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const route = useRoute();
// 是否是添加就诊人
const isAdd = ref(false);
// 已存在就诊人信息
const patientInfoList = ref<updatePatientType[]>([]);
// 修改就诊人信息
const updatePatientInfo = ref<patientInfoItemType>()
// 请求城市列表参数
const parentId = ref(86);
// 省数据
const provinceList = ref<{ value: number; label: string }[]>();
// 地址信息列表
// const addressInfoList = <cityItemType>ref([]);
// 级联选择器ref
const cascader = ref();
// 修改就诊人信息ref
const editBtn = ref();
const redirect = ref<{ type: string; id: string }>();
// 表单收集信息
const formData = ref<addPatientType>({
  // 详细地址
  address: "",
  // 选择地址
  addressSelected: [""],
  // 就诊人出生日期
  birthdate: "",
  // 证件号码
  certificatesNo: "",
  // 证件类型
  certificatesType: "",
  id: 0,
  // 自费或医保
  isInsure: 1,
  // 就诊人婚姻状况
  isMarry: 0,
  // 就诊人姓名
  name: "",
  // 就诊人电话号码
  phone: "",
  // 就诊人性别
  sex: 1,
  // 联系人信息(选填)
  contactsCertificatesNo: "",
  contactsCertificatesType: "",
  contactsName: "",
  contactsPhone: "",
});

onMounted(async () => {
  getPatientList();
  const res: cityItemType[] = await reqCityList(parentId.value);
  console.log("res", res);
  provinceList.value = res.map((item) => {
    return {
      value: item.id,
      label: item.name,
    };
  });
  // console.log(res);
  console.log("query", route.query);
});

// 获取就诊人信息列表
const getPatientList = async () => {
  try {
    patientInfoList.value = await reqPatientList();
  } catch (e) {}
};

// 获取城市信息
const props: CascaderProps = {
  lazy: true,
  async lazyLoad(node, resolve) {
    console.log(node);
    const { level, value } = node;
    const nodes: any = [];

    try {
      const res: cityItemType[] = await reqCityList(Number(value));
      res.map((item) => {
        const nodeItem = {
          value: item.id,
          label: item.name,
          leaf: level >= 2,
        };
        nodes.push(nodeItem);
      });
      resolve(nodes);
    } catch (e) {}
  },
};

// 级联选择器选择地址
const selectAddress = () => {
  console.log(cascader.value.getCheckedNodes()[0].text);
  formData.value.addressSelected =
    cascader.value.getCheckedNodes()[0].pathLabels;
};

// 添加或编辑就诊人
const addPatient = async () => {
  try {
    if (route.query.type === "edit") {
      await reqUpdatePatient(updatePatientInfo.value!)
    } else {
      await reqAddPatient(formData.value);
      ElMessage.success("添加就诊人成功");
      isAdd.value = false;
      getPatientList();
      // console.log(formData.value);
    }
  } catch (e) {
    ElMessage.error("添加就诊人失败");
  }
};

// 修改就诊人信息
const updatePatient = async (id: number) => {
  try {
    // await reqUpdatePatient();
    let type = editBtn.value[0].dataset.type;
    router.push(`/user/patient?type=${type}&id=${id}`);
    getPatientAuth(id);
    // console.log("query",route.query);
  } catch (e) {}
};

// 获取就诊人信息
const getPatientAuth = async (id: any) => {
  try {
    updatePatientInfo.value = await reqPatientAuth(id);
  } catch (e) {}
};

// 添加就诊人页重写就诊人信息
const rewriteForm = () => {
  formData.value = {
    // 详细地址
    address: "",
    // 选择地址
    addressSelected: [""],
    // 就诊人出生日期
    birthdate: "",
    // 证件号码
    certificatesNo: "",
    // 证件类型
    certificatesType: "",
    id: 0,
    // 自费或医保
    isInsure: 1,
    // 就诊人婚姻状况
    isMarry: 0,
    // 就诊人姓名
    name: "",
    // 就诊人电话号码
    phone: "",
    // 就诊人性别
    sex: 1,
    // 联系人信息(选填)
    contactsCertificatesNo: "",
    contactsCertificatesType: "",
    contactsName: "",
    contactsPhone: "",
  };
};

const deletePatient = async (id: number) => {
  try {
    ElMessageBox.confirm('确认删除该联系人吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDeletePatient(id);
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      getPatientList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })


  } catch (e) {}
};

watch(
  route,
  () => {
    // console.log("111",route.query);
    // console.log(redirect.value);
    console.log("1111111111111", route.query);
    redirect.value = route.query as { type: string; id: string };
    console.log(redirect.value);
    if (redirect.value!.type) {
      isAdd.value = true;
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.header .title {
  font-size: 21px;
}
.cardHeader {
  box-sizing: border-box;
  /* background-color: #E5E5E5; */
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.allAuthCard {
  display: flex;
  flex-direction: row;
  justify-content: start;
  flex-wrap: wrap;
}
</style>
